<?php

/**
 * alltosun.com 门店控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 刘德洪 (Liudh@alltosun.com) $
 * $Date: 20151124 $
 * $Id$
 */
class Action
{
    private $per_page = 50;

    /**
     * 显示列表
     */
    public function index() {

        $page_no = $region_problem = $status = $progress = $search_filter = $is_delete = $type = $movie_type = $no_long_lati = $no_cert_company = $no_id_card = $is_multiple = $multiple_id = $is_excel = null;

        extract(URLTracker::init(array(
            'page_id' => 1,
            'status' => -1,
            'progress' => '-1',
            'search_filter' => array(),
            'is_delete' => 1,
            'type' => '-1',
            'movie_type' => -1,
            'no_long_lati' => 0,
            'no_cert_company' => 0,
            'no_id_card' => 0,
            'is_multiple' => 0,
            'multiple_id' => 0,
            'is_excel' => 0,
            'region_problem' => 0,
        )));

        // 拼装搜索条件

        $filter = array();

        //获取当前用户可看的区域
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $filter['id'] = store_helper::get_store_ids_by_admin_user();
            if (!$filter['id']) {
                $filter['id'] = -1;
            }
        }

        if (isset($search_filter['id']) && $search_filter['id']) {
            $filter['id'] = $search_filter['id'];
        }

        if ($type != -1) {
            $filter['type'] = $type;
        }

        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter['`title` LIKE '] = '%' . $search_filter['title'] . '%';
        }

        if (isset($search_filter['title_branch']) && $search_filter['title_branch']) {
            $filter['`title_branch` LIKE '] = '%' . $search_filter['title_branch'] . '%';
        }

        if (isset($search_filter['dealer_name']) && $search_filter['dealer_name']) {
            $dealer_ids = user_helper::get_user_ids_by_realname($search_filter['dealer_name']);
            if (!$dealer_ids) {
                $dealer_ids = user_helper::get_user_ids_by_nickname($search_filter['dealer_name']);
            }
            if ($dealer_ids) {
                $filter['agency_id'] = $dealer_ids;
            }
        }

        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $store_user_ids = user_helper::get_user_ids_by_realname($search_filter['realname']);
            if (!$store_user_ids) {
                $store_user_ids = user_helper::get_user_ids_by_nickname($search_filter['realname']);
            }
            if ($store_user_ids) {
                $filter['user_id'] = $store_user_ids;
            }
        }

        if (isset($search_filter['mobile']) && $search_filter['mobile']) {
            $store_user_id_list = user_helper::get_user_ids_by_mobile($search_filter['mobile']);
            if ($store_user_id_list) {
                if (isset($filter['user_id'])) {
                    $filter['user_id'] = array_intersect($filter['user_id'], $store_user_id_list);
                } else {
                    $filter['user_id'] = $store_user_id_list;
                }
            }
        }

        if (isset($search_filter['district_id']) && $search_filter['district_id']) {
            $filter['district_id'] = $search_filter['district_id'];
            $area = _widget('area')->get_area_info_by_area_code($search_filter['district_id']);
            Response::assign('area', $area);
        } elseif (isset($search_filter['city_id']) && $search_filter['city_id']) {
            $filter['city_id'] = $search_filter['city_id'];
            $area = _widget('area')->get_area_info_by_area_code($search_filter['city_id']);
            Response::assign('area', $area);
        } elseif (isset($search_filter['province_id']) && $search_filter['province_id']) {
            $filter['province_id'] = $search_filter['province_id'];
            $area = _widget('area')->get_area_info_by_area_code($search_filter['province_id']);
            Response::assign('area', $area);
        }

        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'] . ' 23:59:59';
        }

        if ('-1' != $status) {
            $filter['status'] = $status;
        } else {
            $filter['status >= '] = 0;
        }

        // 没有经纬度
        if ($no_long_lati) {
            $filter['(`longitude`'] = 0;
            $filter['OR `latitude`'] = 0;
            $filter[') AND 1'] = 1;
        }

        // 传-1的时候查看所有的信息
        if ($is_delete != -1) {
            $filter['is_delete'] = $is_delete;
        }

        if ($region_problem != 0) {
            $filter['(`province_id`'] = 0;
            $filter['OR `city_id`'] = 0;
            $filter['OR `district_id`'] = 0;
            $filter[') AND 1'] = 1;
        }

        $filter['is_enable'] = 1;
        $filter['`agency_id` !='] = 0;

        if ($is_excel != 1) {
            $store_list = get_data_list('store', enable_filter($filter), ' order BY `id` DESC ', $page_no, $this->per_page);
        } else {
            $store_list = get_data_list('store', enable_filter($filter), ' order BY `id` DESC ', $page_no, 1000);
        }

        if ($store_list) {
            $type_arr = store_config::$type_arr;
            foreach ($store_list as $k => $v) {
                if ($v['owner_id'] > 0) {
                    $user_info = _uri('user', $v['owner_id']);
                    if ($user_info) {
                        $store_list[$k]['user_name'] = $user_info['user_name'];
                        $store_list[$k]['mobile'] = $user_info['mobile'];
                    }
                }
                if (isset($type_arr[$v['type']])) {
                    $store_list[$k]['type_name'] = $type_arr[$v['type']];
                }
                if ($v['agency_id']) {
                    $dealer_info = _uri('user', $v['agency_id']);
                    if ($dealer_info) {
                        $store_list[$k]['dealer_name'] = $dealer_info['realname'];
                        $store_list[$k]['dealer_mobile'] = $dealer_info['mobile'];
                    }
                }

                // 添加门店下单数(实时数据)
                $order_filter = array();
                if (isset($filter['add_time >='])) {
                    $order_filter['add_time >='] = $filter['add_time >='];
                }
                if (isset($filter['add_time <='])) {
                    $order_filter['add_time <='] = $filter['add_time <='];
                }
                if (!empty($order_filter)) {
                    $store_list[$k]['order_period_sum'] = order_helper::get_store_order_num($v['id'], $order_filter);
                }
                $store_list[$k]['order_sum'] = order_helper::get_store_order_num($v['id']);
            }
            if ($is_excel == 1) {
                $this->export_excel($store_list);
            }
        }

        Response::assign('store_list', $store_list);
        Response::assign('status', $status);
        // Response::assign('type', $type);
        // Response::assign('movie_type', $movie_type);
        Response::assign('is_delete', $is_delete);

        Response::assign('progress', $progress);
        Response::assign('search_filter', $search_filter);
        Response::display('admin/store_list.html');
    }

    /**
     * 修改状态
     */
    public function change_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', -1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $info = _uri('store', $id);
        if ($status == $info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        _model('store')->update($id, array('status' => $status));

        return 'ok';
    }

    /**
     * 恢复运营
     */
    public function recover_store() {
        $id = Request::getParam('id', '0');
        $extra = Request::getParam('extra', '');
        $store_type = Request::getParam('store_type', -1);

        $extra = substr($extra, 0, 100);

        if (!$id) {
            return '请选择要更改的内容';
        }

        $info = _uri('store', $id);
        //         if (store_config::STATUS_NORMAL == $info['status']) {
        //             return '已经执行过此操作，不用重复提交';
        //         }

        _model('store')->update($id, array('status' => store_config::STATUS_NORMAL, 'extra' => $extra));

        if ($store_type == -1) {
            Response::redirect(AnUrl('store/admin'));
        } else {
            Response::redirect(AnUrl('store/admin/movie_store'));
        }

    }

    /**
     * 审核门店,显示门店信息
     */
    public function verify_store() {
        $id = Request::getParam('id', 0);
        $is_delete = Request::getParam('is_delete', 1);
        $store_type = Request::getParam('store_type', -1);

        if (!$id) {
            return '请选择门店!';
        }

        $info = _uri('store', $id);


        if ($info) {

            // 获取分店店长,总店店长和签约人员姓名
            $user_info = user_helper::get_user_info($info['user_id']);
            $owner_info = user_helper::get_user_info($info['owner_id']);
            $sign_user_info = user_helper::get_user_info($info['sign_user_id']);

            // 获取主店信息
            $user_store_info = store_helper::get_user_store($info['owner_id']);
            if ($user_store_info) {
                //                 if ($user_store_info['cert_company']) {
                //                     $user_store_info['cert_company'] = _image($user_store_info['cert_company'], 'store-small');
                //                 }
                //                 if ($user_store_info['cert_idcard_front']) {
                //                     $user_store_info['cert_idcard_front'] = _image($user_store_info['cert_idcard_front'], 'store-small');
                //                 }
                //                 if ($user_store_info['cert_idcard_back']) {
                //                     $user_store_info['cert_idcard_back'] = _image($user_store_info['cert_idcard_back'], 'store-small');
                //                 }
                // 处理主店信息
                Response::assign('user_store_info', $user_store_info);
            }

            //  处理门店信息
            $store_info = array(
                'id' => $info['id'],
                'user_name' => $user_info['realname'], //分店店长
                'owner_name' => @$owner_info['realname'], // 总店店长
                'sign_user_name' => $sign_user_info['realname'], // 签约人员
                'sign_user_mobile' => $sign_user_info['mobile'], // 签约人员的手机号
                'sign_time' => $info['sign_time'], // 签约时间
                'type' => store_config::$type_arr[$info['type']], // 门店类型
                'score' => $user_info['score'], //积分
                'level' => score_record_helper::get_user_score_level($user_info['score']) . '级', // 门店等级
                'address' => $info['address'], // 门店地址
                'longitude' => $info['longitude'], // 经度
                'latitude' => $info['latitude'], // 纬度
                'store_title' => $info['title'] . '-' . $info['title_branch'], // 门店名称
                //                 'cover'            => _image($info['cover'], 'store-small'), // 门头图
                'cover' => $info['cover'], // 门头图
                'status' => $info['status'], // 门店状态  1=>试运营 2=>正常 3=>撤店
                'is_delete' => $info['is_delete']
            );

            $store_device_list = array();
            foreach (device_config::$TYPES as $k => $v) {
                $list = device_helper::get_store_typed_device_by_store_id($id, $v['id']);
                if ($list) {
                    $store_device_list[$k]['res_name'] = $v['id'];
                    $store_device_list[$k]['res_name_str'] = $v['name'];
                    $store_device_list[$k]['device_list'] = $list;
                }
            }

            $store_info['store_device_list'] = $store_device_list;
        }

        Response::assign('store_type', $store_type);
        Response::assign('is_delete', $is_delete);
        Response::assign('store_info', $store_info);
        Response::display('admin/verify_store.html');
    }


    /**
     * 编辑门店信息
     */
    public function edit() {
        $id = Request::getParam('id', 0);
        $store_type = Request::getParam('store_type', -1);

        if (!$id) {
            return '请选择门店';
        }

        $store_info = store_helper::get_store($id);
        if (!$store_info) {
            return '此门店不存在';
        }
        $role_id = user_helper::get_admin_role_id();
        $user_info = user_helper::get_user_info($store_info['user_id']);
        if (!$user_info) {
            return '掌柜不存在';
        }

        $store_info['user_name'] = $user_info['realname'] ? $user_info['realname'] : $user_info['nickname'];
        $agency_info = user_helper::get_user_info($store_info['agency_id']);
        $store_info['dealer_name'] = !empty($agency_info['realname']) ? $agency_info['realname']
            : $agency_info['nickname'];
        if ($store_info['agency_id'] == $store_info['marketing_id']) {
            $store_info['marketing_name'] = '';
        } else {
            $marketing_info = user_helper::get_user_info($store_info['marketing_id']);
            $store_info['marketing_name'] = @$marketing_info['realname'] ? $marketing_info['realname']
                : $marketing_info['nickname'];
        }

        if ($store_info['district_id']) {
            $area = _widget('area')->get_area_info_by_area_code($store_info['district_id']);
        } elseif ($store_info['city_id']) {
            $area = _widget('area')->get_area_info_by_area_code($store_info['city_id']);
        } elseif ($store_info['province_id']) {
            $area = _widget('area')->get_area_info_by_area_code($store_info['province_id']);
        } else {
            $area = array();
        }

        // 门店图片
        $store_info['cover'] = _image($store_info['cover']);

        // 获取合伙人列表
        $agency_list = user_helper::get_all_dealers_info();

        // 市场人员列表
        $marketing_list = dealers_helper::get_marketing_list_by_agency_id($store_info['agency_id']);
        array_unshift($marketing_list, user_helper::get_user_info($store_info['agency_id']));
        
        Response::assign('role_id', $role_id);
        Response::assign('id', $id);
        Response::assign('area', $area);
        Response::assign('store_type', $store_type);
        Response::assign('store_info', $store_info);
        Response::assign('marketing_list', $marketing_list);
        Response::assign('agency_list', $agency_list);
        Response::display('admin/edit.html');
    }

    /**
     * 更新门店信息
     */
    public function update() {
        $info = Request::getParam('info', array());
        $province = Request::getParam('province');
        $city = Request::getParam('city');
        $county = Request::getParam('county');
        $store_id = $info['id'];
        $store_type = Request::getParam('store_type', -1);
        $cinema_type = Request::getParam('cinema_type', 0);
        $movie_type = Request::getParam('movie_type', 0);

        $store_info = array();
        // 门店详细地址
        $store_info['address'] = $info['address'];
        // 门店后缀名
        $store_info['title_branch'] = $info['title_branch'];
        // 服务合伙人
        $store_info['service_agency_id'] = $info['service_agency_id'];

        // 市场人员
        if ($info['marketing_id'] == 0) {
            $info['marketing_id'] = $info['agency_id'];
        }
        $store_info['marketing_id'] = $info['marketing_id'];

        $store = _uri('store', $store_id);
        if ($store) {
            // 只有影院门店有影院类型
            if ($store['type'] == 100) {
                $store_info['movie_type'] = $movie_type;
                // 只有直营(1)和加盟(2)的门店有院线类型
                if ($movie_type == 1 || $movie_type == 2) {
                    $store_info['cinema_type'] = $cinema_type;
                }
                $store_info['is_allow_credit'] = $info['is_allow_credit'];
            }
        } else {
            return '未找到门店信息';
        }
        // 地区码处理
        if ($county) {
            $area_code = $county;
        } elseif ($city) {
            $area_code = $city;
        } elseif ($province) {
            $area_code = $province;
        } else {
            $area_code = 0;
        }

        if ($area_code) {
            if (substr($area_code, 4, 2) != '00') {
                $store_info['district_id'] = $area_code;
                $store_info['city_id'] = substr($area_code, 0, 4) . '00';
                $store_info['province_id'] = substr($area_code, 0, 2) . '0000';
            } elseif (substr($area_code, 2, 2) != '00') {
                $store_info['district_id'] = 0;
                $store_info['city_id'] = substr($area_code, 0, 4) . '00';
                $store_info['province_id'] = substr($area_code, 0, 2) . '0000';
            } elseif (substr($area_code, 0, 2) != '00') {
                $store_info['district_id'] = 0;
                $store_info['city_id'] = 0;
                $store_info['province_id'] = substr($area_code, 0, 2) . '0000';
            }
        }

        $k = 'cover';
        if (isset($_FILES[$k]) && $_FILES[$k]['tmp_name']) {
            $image_info = upload_file($_FILES[$k], false);
            if ($image_info) {
                $store_info[$k] = isset($image_info['file_path']) ? $image_info['file_path'] : $image_info;
            }
        }

        $affected = _model('store')->update($store_id, $store_info);
        if ($store_type == -1) {
            Response::redirect(AnUrl('store/admin'));
        } else {
            Response::redirect(AnUrl('store/admin/movie_store'));
        }

    }


    /**
     *
     * 获取门店设备绑定记录
     */
    public function get_store_device_record() {
        $id = Request::getParam('id', 0);
        $is_delete = Request::getParam('is_delete', 1);
        $store_type = Request::getParam('store_type', -1);

        if (!$id) {
            return false;
        }

        $store_info = _uri('store', $id);

        $record_list = array();
        $record_list = store_helper::get_store_device_record($id);

        Response::assign('store_type', $store_type);
        Response::assign('is_delete', $is_delete);
        Response::assign('store_info', $store_info);
        Response::assign('record_list', $record_list);
        Response::display('admin/store_device_record.html');

    }

    /**
     * 获取门店设备信息
     */
    public function get_store_device_list() {
        $id = Request::getParam('id', 0);
        $is_delete = Request::getParam('is_delete', 1);
        $store_type = Request::getParam('store_type', -1);

        if (!$id) {
            return false;
        }

        $store_info = _uri('store', $id);

        $record_list = device_helper::get_store_all_device_list_by_store_id($id);

        Response::assign('store_type', $store_type);
        Response::assign('is_delete', $is_delete);
        Response::assign('store_info', $store_info);
        Response::assign('record_list', $record_list);
        Response::display('admin/store_device_list.html');

    }

    /**
     * 删除门店
     */
    public function delete_store() {
        $id = Request::getParam('id');
        if (!$id) {
            return '请选择要删除的内容';
        }
        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $store_info = _uri('store', (int)$v);
            if (!$store_info) {
                continue;
            }

            if (1 == $store_info['is_delete']) {
                _model('store')->update($v, array('is_delete' => 0));
            }
        }

        return 'ok';

    }

    /**
     * 取消删除
     */
    public function undelete_store() {
        $id = Request::getParam('id');
        if (!$id) {
            return '请选择要删除的内容';
        }
        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $store_info = _uri('store', (int)$v);
            if (!$store_info) {
                continue;
            }

            if (0 == $store_info['is_delete']) {
                _model('store')->update($v, array('is_delete' => 1));
            }
        }

        return 'ok';
    }


    /**
     * 三维数组转换
     * @return array
     */
    private function exchangeArr($arr) {
        if (!is_array($arr)) {
            return;
        }
        foreach ($arr as $key => $value) {
            foreach ($value as $k => $v) {
                $new_arr[$k][$key] = $v;
            }
        }
        return $new_arr;
    }

    /**
     * 商店导出信息
     */
    public function export_excel($list = array()) {
        $lines = array();
        foreach ($list as $k => $v) {
            if ($v['status'] == 1) {
                $v['store_status'] = "未审核";
            } elseif ($v['status'] == 2) {
                $v['store_status'] = "正常";
            } else {
                $v['store_status'] = "撤店";
            }
            array_push($lines, array(
                $v['id'],
                $v['title'] . '(' . $v['title_branch'] . ')',
                $v['mobile'],
                $v['dealer_name'],
                $v['dealer_mobile'],
                $v['address'],
                $v['type_name'],
                $v['add_time'],
                $v['store_status'],
                $v['order_period_sum'],
                $v['order_sum'],
            ));
        }
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K');
        // 第一排的标题
        $col_title_arr = array(
            '店铺id',
            '店铺名称',
            '店长手机号',
            '合伙人',
            '合伙人手机号',
            '店铺地址',
            '掌柜门店类型',
            '添加时间',
            '掌柜门店状态',
            '订单数',
            '订单总数',
        );

        foreach ($col_arr as $k => $v) {
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v . "1", $col_title_arr[$k]);
        }
        //填充单元格
        $key = 2;
        foreach ($list as $k => $v) {
            foreach ($col_arr as $k2 => $v2) {
                $place = $v2 . $key;
                $objActSheet->setCellValue($place, $lines[$k][$k2]);
            }
            $key++;
        }

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = date("Y-m-d") . "门店统计信息统计.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=" . $title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }

}
